package com.humh.certification.controller;

import com.humh.certification.common.CommonResult;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>Token 接口</p>
 * Create by hgx61 at 2024/10/18
 */

@RestController
@RequestMapping("/tokens")
public class TokenController {

  private static Map<String,String> userMap=new HashMap<>(); // 用户信息
  private static final String TOKEN_PREFIX="token:";
  private static Set<String> tokenSet=new HashSet<>(); // token 集合

  /**
   * 初始化用户信息
   */
  static {
    userMap.put("admin","admin");
    userMap.put("user","user");
    userMap.put("test","test");
    userMap.put("humh","123456");
  }


  /**
   * 获取token
   * @param userName
   * @param password
   * @return
   */
  @GetMapping("/getToken")
  public CommonResult<String> getToken(String userName, String password) {
    if (!userMap.containsKey(userName)) {
      return CommonResult.error(-1001,"用户不存在");
    }

    if (!userMap.get(userName).equals(password)) {
      return CommonResult.error(-1002,"密码错误");
    }

    String token = TOKEN_PREFIX+userName+password;
    tokenSet.add(token);
    return CommonResult.success(token);
  }

  /**
   * 验证token
   * @param token
   * @return
   */
  @GetMapping("/checkToken")
  public CommonResult<String> verifyToken(String token) {

    // 验证token 是否存在
    if (!tokenSet.contains(token)) {
      return CommonResult.error(-1003,"token不存在");
    }

    return CommonResult.success(token);
  }

}
